package home

import (
	// "fmt"

	"gitee.com/chenrh/finego/app"
	"gitee.com/chenrh/finego/backends/crawler"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
)

// FilmController 首页电影控制器
type FilmController struct {
	// Optionally: context is auto-binded by Iris on each request,
	// remember that on each incoming request iris creates a new UserController each time,
	// so all fields are request-scoped by-default, only dependency injection is able to set
	// custom fields like the Service which is the same for all requests (static binding).
	Ctx iris.Context
}

// BeforeActivation Mvc 注册路由
func (c *FilmController) BeforeActivation(b mvc.BeforeActivation) {
	b.Handle("POST", "/film/magnet", "PostFilmMagnet")
}

// GetFilm 首页
func (c *FilmController) GetFilm() mvc.Result {

	filmCrawler := crawler.Dy2018ComCrawler{}
	filmMaps, err := filmCrawler.StartCrawler()
	if err != nil {
		app.LoggerWithCtx(c.Ctx).Errorf("爬取电影数据时报错：%s", err)
	}

	return mvc.View{
		Name: "film.html",
		Data: iris.Map{
			"Title": app.AppConfig.AppName,
			"Films": filmMaps,
		},
	}
}

// PostFilmMagnet 获取磁力链接 /film/magnet
func (c *FilmController) PostFilmMagnet() {
	url := c.Ctx.FormValue("url")

	if len(url) == 0 {
		c.Ctx.JSON(iris.Map{"magnet": "必要参数[url]为空"})
	}

	filmCrawler := crawler.Dy2018ComCrawler{}
	magnet, err := filmCrawler.CrawlerMagnet(url)
	if err != nil {
		app.LoggerWithCtx(c.Ctx).Errorf("爬取电影数据时报错：%s", err)
		c.Ctx.JSON(iris.Map{"magnet": err})
	}

	c.Ctx.JSON(iris.Map{"magnet": magnet})
}
